package com.seckill.controller;
import com.alibaba.fastjson.JSON;
import com.seckill.model.KillGoods;
import com.seckill.model.userInfo;
import com.seckill.service.KillGoodsService;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.DirectExchange;

import org.springframework.amqp.core.Queue;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/Kill")
public class KillGoodsController {

    @Autowired
    KillGoodsService killGoodsService;
    @Autowired
    ThymeleafViewResolver thymeleafViewResolver;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    AmqpAdmin amqpAdmin;




    @ResponseBody
    @RequestMapping("/All")
    public String KillGoodsAll(HttpServletRequest request, HttpServletResponse response, Model model){
        String html="";

        ValueOperations<String, String> redis = stringRedisTemplate.opsForValue();
        html=redis.get("seckill:killGoods");

        if(!StringUtils.isEmpty(html)){
            return html;
        }

        List<KillGoods> killGoods = killGoodsService.KillGoodsAll();

        model.addAttribute("goodsList",killGoods);



        WebContext webContext = new WebContext(request,response,request.getServletContext(),response.getLocale(),model.asMap());
        html=thymeleafViewResolver.getTemplateEngine().process("KillGoods",webContext);

        if(!StringUtils.isEmpty(html)){
            redis.set("seckill:killGoods",html,120, TimeUnit.SECONDS);
        }

        return html;
    }

    @ResponseBody
    @RequestMapping("/KillID")
    public String KillGoodsById(HttpSession session,Integer killid ,HttpServletRequest request, HttpServletResponse response, Model model){
        String html="";

        SetOperations<String, String> set = stringRedisTemplate.opsForSet();
        ValueOperations<String, String> redis = stringRedisTemplate.opsForValue();

        html=redis.get("seckill:Goods:"+killid);

        if(!StringUtils.isEmpty(html)){
            return html;
        }

        KillGoods killGoods = killGoodsService.KillGoodsById(killid);

        Long start = killGoods.getStartdate().getTime();
        Long end=killGoods.getEnddate().getTime();

        Date date = new Date();
        long time = date.getTime();

        String  flag;

        if(time<start){
            flag="start";
        }else if(time>end){
            flag="end";
        }else {
            flag="underway";
        }


        model.addAttribute("goods",killGoods);
        model.addAttribute("flag",flag);

        WebContext webContext = new WebContext(request,response,request.getServletContext(),response.getLocale(),model.asMap());

        html=thymeleafViewResolver.getTemplateEngine().process("Goods",webContext);



        if(!StringUtils.isEmpty(html)){
            redis.set("seckill:Goods:"+killid,html,120, TimeUnit.SECONDS);

        }


        redis.set("seckill:stock:"+killid, String.valueOf(killGoods.getStockcount()));

        redis.set("seckill:kill:"+killid, JSON.toJSONString(killGoods));

        return html;
    }

    @ResponseBody
    @RequestMapping("/One")
    public String KillOne(int killid,HttpSession session){

        ValueOperations<String, String> redis = stringRedisTemplate.opsForValue();
        SetOperations<String, String> set = stringRedisTemplate.opsForSet();


        userInfo user = (userInfo) session.getAttribute("user");


        if(user==null){
            return "<a href='/login.html'>请登录</a>";
        }


        KillGoods killGoods = killGoodsService.KillGoodsById(killid);

        Boolean member = set.isMember("killgoods"+killid, killid + "" + user.getUserId());
        if(member){
            return "该商品已秒杀过";
        }

        int stock = Integer.parseInt(redis.get("seckill:stock:"+killid));
        if(stock<=0){
            return "秒杀商品预设库存已没有";
        }

        redis.decrement("seckill:stock:"+killid);


//        Jedis jedis=new Jedis("192.168.104.54");
//
//        String script="if redis.call('get',KEYS[1])>'0'  then  redis.call('decr',KEYS[1])   end";
//
//        jedis.eval(script,1,"seckill:stock:"+killid);



        set.add("killgoods"+killid,killid + "" + user.getUserId());


        Map<String,Object> map = new HashMap();
        map.put("userid",user.getUserId());
        map.put("killid",killid);


        DirectExchange exchange = new DirectExchange("killExchange",true,false);
        amqpAdmin.declareExchange(exchange);

        Queue queue = new Queue("killQueue",true,false,false);
        amqpAdmin.declareQueue(queue);

        Binding binding = new Binding("killQueue",Binding.DestinationType.QUEUE,"killExchange","KillRoute",null);
        amqpAdmin.declareBinding(binding);

        rabbitTemplate.convertAndSend("killExchange","KillRoute",map);


        stringRedisTemplate.delete("seckill:Goods:"+killid);


        return "秒杀成功";
    }
}
